import os, datetime

date_sale = {}
is_first_line = True
file_path = os.path.join(os.getcwd(), "01-exercise/21-40/data/date_sale_data.txt")

# 修复编码参数格式问题
with open(file_path, 'r', encoding='utf-8') as fin:
    for line in fin:
        '''
        if is_first_line:
            is_first_line = False
            continue
            '''
        line = line.strip()
        # 处理可能的空格和制表符混用情况
        parts = line.split()
        if len(parts) < 2:  # 跳过无效行
            continue
        date, sale_number = parts[0], parts[-1]
        try:
            date_sale[date] = float(sale_number)
        except ValueError:
            continue

def get_diff_days(date_str, days):
    # 修复：正确使用strptime转换日期字符串
    curr_date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
    timedelta_val = datetime.timedelta(days=-days)
    # 修复：返回格式化的日期字符串
    return (curr_date + timedelta_val).strftime('%Y-%m-%d')

# 修复：使用正确的字典变量名和方法
for date, sale_number in date_sale.items():
    date7 = get_diff_days(date, 7)
    sale_number7 = date_sale.get(date7, 0)
    if sale_number7 == 0:
        print(f"{date} {sale_number:.2f} (无7天前数据)")
    else:
        week_diff = (sale_number - sale_number7) / sale_number7 * 100
        print(f"{date}: {sale_number:.2f} | 周同比: {week_diff:+.2f}% ({date7}: {sale_number7:.2f})")